#include <iostream>
#include<mutex>
#include "pthread.hpp"
#include"lock_guard.hpp"
using namespace pthread_moudle;
// 公共资源，票数
int g_tickets = 1000;

//pthread_mutex_t g_mutex=PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;//全局或静态定义不需要手动init与销毁
class ThreadData
{
public:
    ThreadData(std::string name, int &tickets,pthread_mutex_t& mutex)
        : _name(name), _tickets(tickets), _self_ticket(0),_mutex(mutex)
    {
    }
    int &GetSelfTicket()
    {
        return _self_ticket;
    }
    std::string name()
    {
        return _name;
    }
    int &TotalTickets()
    {
        return _tickets;
    }
    pthread_mutex_t& mutex()
    {
        return _mutex;
    }
    ~ThreadData()
    {
    }

private:
    std::string _name;
    int _self_ticket; // 每个线程抢到的票数
    int &_tickets;    // 剩余的总票数
    pthread_mutex_t& _mutex;//锁
};

void routine(ThreadData *td)
{
    std::cout << "enter rountine" << std::endl;
    while (true)
    {
        Lockguard guard(&td->mutex());
        //pthread_mutex_lock(&td->mutex());
        if (td->TotalTickets() > 0)
        {
            usleep(1000);
            printf("i'm %s ! Total tickets:%d\n", td->name().c_str(), td->TotalTickets());
            td->GetSelfTicket()++;
            td->TotalTickets()--;
            //pthread_mutex_unlock(&td->mutex());
        }
        else
        {
            //pthread_mutex_unlock(&td->mutex());
            break;
        }
    }
}
int main(int argc, char *argv[])
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);//初始化锁
    if (argc != 2)
    {
        std::cout << "please enter right parameter!" << std::endl;
        return -1;
    }
    int num = std::stoi(argv[1]);

    std::vector<Thread<ThreadData *>> threads;
    std::vector<ThreadData *> datas;
    // 创建一批线程
    for (int i = 0; i < num; i++)
    {
        std::string name = "Thread---" + std::to_string(i + 1);
        ThreadData *td = new ThreadData(name, g_tickets,mutex);
        threads.emplace_back(routine, td, name);
        datas.push_back(td);
    }
    std::cout << threads.size() << std::endl;

    // 启动线程
    for (auto &thread : threads)
    {

        bool flag = thread.start();
        if (flag)
            std::cout << "启动成功" << std::endl;
        else
            std::cout << "启动失败" << std::endl;
    }

    // 等待线程
    for (auto &thread : threads)
    {
        thread.join();
    }
    pthread_mutex_destroy(&mutex);//销毁锁
    for (auto &e : datas)
    {
        std::cout << e->name() << " GetSelfTicket:" << e->GetSelfTicket() << std::endl;
        delete e;
    }
    return 0;
}